package cn.jfast.framework.jdbc.log;

import cn.jfast.framework.log.LogFactory;
import cn.jfast.framework.log.Logger;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;


public class ConnectionLogger implements InvocationHandler{
	
	private Logger log = LogFactory.getLogger(ConnectionLogger.class);
	private List<Object> params = new ArrayList<Object>();
	private String sql = "";
    private Connection conn;
	private String targetMethod;
    
    public ConnectionLogger(Connection conn){
    	this.conn = conn;
    }

	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		try {
			if (method.getName().equals("prepareStatement")) {
				sql = String.valueOf(args[0]).replaceAll("\\?", "%s");
				return PreparedStatement.getPreparedStatement((java.sql.PreparedStatement) method.invoke(conn, args),sql,targetMethod);
			} else if (method.getName().equals("setCatalog")){
				targetMethod = String.valueOf(args[0]);
				return null;
			}
			return method.invoke(conn, args);
		} catch (InvocationTargetException e) {
			throw e.getTargetException();
		}
	}

}
